package com.example.demo.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.annotation.IgnoreAuth;
import com.example.demo.entity.pojo.UserVo;
import com.example.demo.entity.pojo.Yonghu;
import com.example.demo.entity.pojo.YonghuLoginVo;
import com.example.demo.service.IYonghuService;
import com.example.demo.utils.R;
import com.example.demo.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户 前端控制器
 * </p>
 *
 * @author author
 * @since 2025-01-09
 */
@RestController
@RequestMapping("/yonghu")
public class YonghuController {
    @Autowired
    private IYonghuService yonghuService;
    //登录
    @PostMapping("/login")
    @IgnoreAuth
    public R login(String username,String password){
        Yonghu yonghu = yonghuService.getOne(new QueryWrapper<Yonghu>().eq("zhanghao",username));
        if(yonghu==null||!(yonghu.getMima().equals(password))){
            return R.error("用户名或密码错误");
        }
        YonghuLoginVo yonghuLoginVo = BeanUtil.copyProperties(yonghu,YonghuLoginVo.class);
        String token = TokenUtil.createToken(username);
        yonghuLoginVo.setToken(token);
        Map<String,Object> map = new HashMap<>();
        map.put("data",yonghuLoginVo);
        map.put("msg","登录成功");
        map.put("code",200);
        return R.ok(map);
    }
    //注册用户信息
    @PostMapping("/register")
    @IgnoreAuth
    public R register(@RequestBody Yonghu yonghu){
        if(yonghuService.getOne(new QueryWrapper<Yonghu>().eq("zhanghao", yonghu.getZhanghao())) !=null) {
            return R.error("用户已存在");
        }
        yonghuService.save(yonghu);
        Map<String,Object> map = new HashMap<>();
        map.put("msg","注册成功");
        map.put("code",200);
        map.put("data",null);
        return R.ok(map);
    }
    //修改用户信息
    @PostMapping("/update")
    public R update(@RequestBody Yonghu yonghu){
        System.out.println(yonghu.getId());
        yonghuService.updateById(yonghu);
        Map<String,Object> map = new HashMap<>();
        map.put("msg","修改成功");
        map.put("code",200);
        map.put("data",null);
        return R.ok(map);
    }
    //删除用户信息
    @PostMapping("/delete")
    public R delete(Long id){
        yonghuService.removeById(id);
        Map<String,Object> map = new HashMap<>();
        map.put("msg","删除成功");
        map.put("code",200);
        map.put("data",null);
        return R.ok(map);
    }
}
